package com.thenie.chat.service.impl;

import com.thenie.chat.service.IDialogSocketService;
import com.thenie.chat.vo.DialogMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @Description DialogSocket服务实现类
 * @Author thenie
 * @Data 2022/5/30 19:30
 */
@Service
public class DialogSocketServiceImpl implements IDialogSocketService {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    /*
    保存离线消息到redis
     */
    @Override
    public boolean saveOfflineMessage(DialogMessage dialogMessage) {
        String uid = dialogMessage.getToFriendId();
        double score = new Long(dialogMessage.getDateTime().getTime()).doubleValue();

        return redisTemplate.opsForZSet().add("dialogMessage:" + uid, dialogMessage, score);
    }

    /*
    是否有自己的离线消息
     */
    @Override
    public boolean existOfflineMessageForMe(String userId) {
        return redisTemplate.hasKey("dialogMessage:"+userId);
    }

    /*
    获取自己的所用离线消息
     */
    @Override
    public List<Object> getAllOfflineMessage(String userId) {
        //按时间升序返回结果
        Set<Object> set = redisTemplate.opsForZSet().range("dialogMessage:" + userId, 0, -1);
        return new ArrayList<>(set);
    }
    /*
    删除消息
     */
    @Override
    public boolean removeOfflineMessageForMe(String userId) {
        return redisTemplate.delete("dialogMessage:"+userId);
    }

}
